package cn.mju.edu.listeners;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUserListner implements HttpSessionListener,HttpSessionAttributeListener 
{

	//侦听属性的改变用HttpSessionAttributeLitener或HttpSessionBindingListener等接口
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("Create Session");

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("Destroy Session");
		HttpSession session = arg0.getSession();
		Object obj = session.getAttribute("user");
		if(obj!=null)
		{
			String sessUserName = obj.toString();
			ServletContext application = arg0.getSession().getServletContext();
			Object obj1 = application.getAttribute("users");
			if(obj1 != null)
			{
				List<String> users = (List<String>)obj1;
				Iterator it = users.iterator();
				while(it.hasNext())
				{
					Object u = it.next();
					String saveUserName = u.toString();
					if(saveUserName.equals(sessUserName))
					{
						users.remove(u);
						application.setAttribute("users", users);
						break;
					}
				}
			}
		}

	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("添加属性值："+arg0.getName() +"="+ arg0.getValue());
		if("user".equals(arg0.getName()))
		{
			ServletContext application = arg0.getSession().getServletContext();
			Object obj = application.getAttribute("users");
			List<String> users =null;
			if(obj != null)
			{
				 users = (List<String>)obj;
				
			}
			else
			{
				users = new ArrayList<String>();
			}
			users.add(arg0.getValue().toString());
			application.setAttribute("users", users);
		}
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("删除属性值："+arg0.getName() +"="+ arg0.getValue());
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("改变属性值："+arg0.getName() +"="+ arg0.getValue());
		
		
	}

}
